﻿using BatteryAPI.Context;
using CommonEntity.BatteryEntity;
using CommonEntity.PackageEntity;
using CommonHelper;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BatteryAPI.Controllers
{
    /// <summary>
    /// Battery相关信息服务接口
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class BatteryController : ControllerBase
    {
        private readonly ILogger<BatteryController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ICapPublisher _capBus;
        private readonly BatteryContext _context;
        private readonly IDatabase _redis;

        public BatteryController(ILogger<BatteryController> logger, IConfiguration configuration, ICapPublisher capPublisher, BatteryContext context, RedisHelper client)
        {
            _logger = logger;
            _configuration = configuration;
            _capBus = capPublisher;
            _context = context;
            _redis = client.GetDatabase();
        }

        /// <summary>
        /// 获取Battery服务IP和端口
        /// </summary>
        /// <returns></returns>
        [Route("BatteryServer")]
        [HttpGet]
        public IActionResult GetBatteryServer()
        {
            return Ok($"【Battery服务】{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}--{Request.HttpContext.Connection.LocalIpAddress}:{_configuration["ConsulSetting:ServicePort"]}");
        }

        /// <summary>
        /// 获取Battery剩余数量
        /// </summary>
        /// <param name="ID">ID</param>
        /// <returns></returns>
        [Route("BatteryCount")]
        [HttpGet]
        public async Task<IActionResult> GetBatteryCountByID(int ID)
        {
            try
            {
                var curCount = await _context.BatteryInfos.Where(q => q.ID == ID).Select(a => a.TotalCount).FirstOrDefaultAsync();
                return Ok(curCount);
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }

        /// <summary>
        /// 创建更新Battery
        /// </summary>
        /// <param name="battery"></param>
        /// <returns></returns>
        [Route("CreateUpdate")]
        [HttpPost]
        public async Task<IActionResult> CreateUpdateBattery(BatteryInfo battery)
        {
            try
            {
                using (var trans = _context.Database.BeginTransaction(_capBus, autoCommit: true))
                {
                    var curBattery = _context.BatteryInfos.FirstOrDefault(batteryinfo => batteryinfo.Capacity == battery.Capacity);
                    if (curBattery == null)
                    {
                        battery.LastProduceTime = DateTime.Now;
                        battery.TotalCount = 1;
                        _context.BatteryInfos.Add(battery);
                    }
                    else
                    {
                        curBattery.LastProduceTime = DateTime.Now;
                        curBattery.TotalCount += 1;
                    }
                    var r = await _context.SaveChangesAsync() > 0;
                    if (r)
                    {
                        //更新redis
                        var batchExe = _redis.CreateBatch();
                        _redis.KeyDelete("BatteryInfos");
                        _context.BatteryInfos.ToList().ForEach(a => batchExe.SetAddAsync("BatteryInfos", JsonConvert.SerializeObject(a)));
                        batchExe.Execute();

                        return Ok();
                    }
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }

        /// <summary>
        /// 组装手机 订阅Battery减少事件
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [NonAction]
        [CapSubscribe("PackageAPI.CreatePhone")]
        public async Task ReduceBattery(PackageInfo message)
        {
            //业务代码
            var batteryInfo = await _context.BatteryInfos.FirstOrDefaultAsync(p => p.ID == message.BatteryID);
            batteryInfo.LastProduceTime = DateTime.Now;
            batteryInfo.TotalCount -= 1;

            await _context.SaveChangesAsync();

            //更新redis
            var batchExe = _redis.CreateBatch();
            _redis.KeyDelete("BatteryInfos");
            _context.BatteryInfos.ToList().ForEach(a => batchExe.SetAddAsync("BatteryInfos", JsonConvert.SerializeObject(a)));
            batchExe.Execute();

        }

    }
}
